package com.huibao.hulibao.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.huibao.hulibao.R;
import com.huibao.hulibao.activity.LoginActivity;
import com.huibao.hulibao.activity.MainActivity;
import com.huibao.hulibao.activity.ServerDetailActivity;
import com.huibao.hulibao.adapter.MsgLvAdapter;
import com.huibao.hulibao.adapter.ServerLvAdapter;
import com.huibao.hulibao.constant.GlobalConstants;
import com.huibao.hulibao.entity.LoginEntity;
import com.huibao.hulibao.entity.MessageEntity;
import com.huibao.hulibao.entity.ResultEntity;
import com.huibao.hulibao.entity.ServerEntity;
import com.huibao.hulibao.utils.MyUtils;
import com.huibao.hulibao.utils.PreUtils;
import com.huibao.hulibao.utils.T;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by lizhaoyong on 2018/5/7.
 */
public class MessageFragmentView extends Fragment {
    private Unbinder unbinder;

    private Context context;
    @BindView(R.id.lv_msg)
    ListView lv_msg;
    @BindView(R.id.tv_msg_head)
    TextView tv_msg_head;
    @BindView(R.id.srl_msg)
    SmartRefreshLayout srl_msg;
    @BindView(R.id.tv_confirm)
    TextView tv_confirm;
    @BindView(R.id.tv_clear)
    TextView tv_clear;
    @BindView(R.id.ll_bottom)
    LinearLayout ll_bottom;


    public MsgLvAdapter mla;

    public MessageEntity me;

    public MainActivity mainActivity;

    public LoginEntity le;

    // 定时刷新
    public Runnable runnable;
    public boolean isWhile = false;

    @OnClick(R.id.tv_confirm)
    public void confirm() {
        if (le != null && me != null) {
            for (int i = 0; i < me.Message.size(); i++) {
                operMessageData("-10", me.Message.get(i).Id, false);
            }
        }
    }

    @OnClick(R.id.tv_clear)
    public void clear() {
        for (int i = 0; i < me.Message.size(); i++) {
            operMessageData("0", me.Message.get(i).Id, false);
        }
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_message, null);
        unbinder = ButterKnife.bind(this, v);
        context = getActivity();
        mainActivity = (MainActivity) getActivity();
        tv_msg_head.requestFocus();

        // 请求数据
        getMessageFromServer();
        // 下拉刷新监听
        srl_msg.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                getMessageFromServer();
            }
        });

//        lv_msg.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                LogUtils.d("点击了");
////                T.show(mainActivity, me.Message.get(position).Msg, 0);
////                if (me != null) {
////                    T.show(mainActivity, me.Message.get(position).Msg, 0);
////                }
//            }
//        });
        autoRefresh();
        return v;
    }


    // 获取服务器消息
    public void getMessageFromServer() {
        // 后台不请求
        if (MyUtils.isApplicationInBackground(mainActivity)) {
            return;
        }

        le = (LoginEntity) PreUtils.getObject(context, "LoginEntity");
        if (le == null) {
            return;
        }

        RequestParams params = new RequestParams(GlobalConstants.URL);
        params.setCacheMaxAge(0);
        // mainActivity.showDialog();

        params.addBodyParameter("q", le.Message.Session + GlobalConstants.URL_MESSAGE + "-");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                srl_msg.finishRefresh();
                mainActivity.closeDialog();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(result);
                    // 登录超时
                    if (jsonObject.toString().contains("\"State\"" + ":" + "\"" + GlobalConstants.LOGIN_TIME_OUT + "\"")) {
                        // 退出登录
                        PreUtils.saveObject(context, "LoginEntity", null);
                        Intent intent = new Intent(context, LoginActivity.class);
                        startActivity(intent);
                        getActivity().finish();
                        return;
                    }
                    me = GlobalConstants.gson.fromJson(jsonObject.toString(), MessageEntity.class);
                    if (me.Message.size() > 0) {
                        ll_bottom.setVisibility(View.VISIBLE);
                    } else {
                        ll_bottom.setVisibility(View.INVISIBLE);
                    }
                    LogUtils.d("result = " + jsonObject.toString());
                    int num = 0;
                    for (int i = 0; i < me.Message.size(); i++) {
                        if (Integer.parseInt(me.Message.get(i).Status) < 0) {
                            num = num + 1;
                        }
                    }

                    if (me != null) {
                        tv_msg_head.setText(context.getString(R.string.nihaiyou) + num + context.getString(R.string.geweiquerendexiaoxi));
                    }
                    mla = new MsgLvAdapter(me.Message, context, MessageFragmentView.this);
                    lv_msg.setAdapter(mla);


                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                srl_msg.finishRefresh();
                mainActivity.closeDialog();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                srl_msg.finishRefresh();
                mainActivity.closeDialog();
            }

            @Override
            public void onFinished() {
                srl_msg.finishRefresh();
                mainActivity.closeDialog();
            }
        });
    }

    public void autoRefresh() {
        if (mainActivity == null) {
            return;
        }

        if (isWhile) {
            return;
        }

        isWhile = true;

        runnable = new Runnable() {
            @Override
            public void run() {
                getMessageFromServer();
                mainActivity.MessageHandler.postDelayed(this, 5000);
            }
        };
        mainActivity.MessageHandler.removeCallbacks(runnable);
        mainActivity.MessageHandler.postDelayed(runnable, 5000);
    }

    public void stopRefresh() {
        if (mainActivity == null) {
            return;
        }
        isWhile = false;
        mainActivity.MessageHandler.removeCallbacks(runnable);
    }

    // 消息处理操作
    public void operMessageData(String status, String mid, final boolean is_show_dialog) {
        RequestParams params = new RequestParams(GlobalConstants.URL);
        params.setCacheMaxAge(0);
//        if (is_show_dialog) {
//            mainActivity.showDialog();
//        }
        JSONObject object = new JSONObject();
        try {
            object.put("mid", mid);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        // 确认和关闭消息
        if (status.equals("-10")) {
            params.addBodyParameter("q", le.Message.Session + GlobalConstants.URL_MESSAGE_OPR_CONFRIM + object.toString());
        } else if (status.equals("0")) {
            params.addBodyParameter("q", le.Message.Session + GlobalConstants.URL_MESSAGE_OPR_CLOSE + object.toString());
        }
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                mainActivity.closeDialog();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(result);
                    // LogUtils.d("result = " + jsonObject.toString());
                    ResultEntity re = GlobalConstants.gson.fromJson(jsonObject.toString(), ResultEntity.class);
                    if (re != null) {
                        if (re.State.equals(GlobalConstants.SUCCESS_CODE)) {
                            // 请求数据刷新页面
                            getMessageFromServer();
                            if (is_show_dialog) {
                                T.show(context, getResources().getString(R.string.chaozuochenggong), 0);
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mainActivity.closeDialog();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                mainActivity.closeDialog();
            }

            @Override
            public void onFinished() {
                mainActivity.closeDialog();
            }
        });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        stopRefresh();
    }
}
